package com.lwbldy.common.tools;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
//import org.apache.commons.httpclient.ConnectTimeoutException;
//import org.apache.commons.httpclient.HttpClient;
//import org.apache.commons.httpclient.HttpException;
//import org.apache.commons.httpclient.HttpMethod;
//import org.apache.commons.httpclient.methods.GetMethod;
//import org.apache.commons.httpclient.methods.PostMethod;
//import org.apache.commons.httpclient.methods.RequestEntity;
//import org.apache.commons.httpclient.methods.StringRequestEntity;
//import org.apache.commons.httpclient.params.HttpConnectionParams;
//import org.apache.commons.httpclient.protocol.Protocol;
//import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;

import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;

import static java.net.Proxy.Type.HTTP;

public class HttpRequest {

    public static void main(String[] args){

    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            connection.setRequestProperty("Origin", "https://www.creditchina.gov.cn");
            connection.setRequestProperty("Referer", "https://www.creditchina.gov.cn/");

            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String sendJSONPost(String jsonStr,String url){
        String result = "";
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");

            OutputStream os = conn.getOutputStream();
            os.write(jsonStr.getBytes("UTF-8"));
            os.close();

            InputStream in = new BufferedInputStream(conn.getInputStream());
            result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
            in.close();
            conn.disconnect();
            return result;
        }catch (Exception e){
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        return result;
    }

//    public static String httpsPost(String url) {
//        //增加下面两行代码
//        Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
//        Protocol.registerProtocol("https", myhttps);
//
//        HttpClient client = new HttpClient();
//        PostMethod post = new PostMethod(url);
//        try {
//            String json = "{\"name\":\"张三\"}";
//            RequestEntity requestEntity = new StringRequestEntity(json ,"application/json" ,"UTF-8");
//            post.setRequestEntity(requestEntity);
//            post.setRequestHeader("Content-Type","application/json");
//            client.executeMethod(post);
//            byte[] responseBody = post.getResponseBody();
//            String result = new String(responseBody,"UTF-8");
//            return result;
//        } catch (HttpException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            post.releaseConnection();
//        }
//        return null;
//    }
//
//    public static String httpsGet(String url){
//        Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
//        Protocol.registerProtocol("https", myhttps);
//        HttpClient client = new HttpClient();
//        HttpMethod get = new GetMethod(url);
//        try {
//            client.executeMethod(get);
//            byte[] responseBody = get.getResponseBody();
//            String result = new String(responseBody,"UTF-8");
//            return result;
//        } catch (HttpException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            get.releaseConnection();
//        }
//        return null;
//    }
//
//
//    public static void main(String[] args) {
//        //发送 GET 请求
//
//        //发送 POST 请求
//        String url = "https://public.creditchina.gov.cn/private-api/catalogSearch?keyword=&scenes=defaultscenario&tableName=credit_fgw_mqqqsj&searchState=2&entityType=2&page=2&pageSize=500";
//        String sr = HttpRequest.httpsGet(url);
//        System.out.println(sr);
//
//        JSONObject jsonObject = JSONObject.parseObject(sr);
//        JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
//        System.out.println("---size:"+jsonArray.size());
//
//        System.out.println("失信被执行人注册地\t\t失信被执行人名称\t\t案号\t\t拖欠天数\t\t涉及金额（人民币）");
//
//        for(int i = 0;i < jsonArray.size();i++){
//            JSONObject jo = jsonArray.getJSONObject(i);
//
//            System.out.printf("%s\t\t%s\t\t%s\t\t%s\t\t%s\n",
//                    jo.getString("sf")+""+jo.getString("cs"),
//                    jo.getString("entname"),
//                    jo.getString("anhao"),
//                    jo.getString("tqts"),
//                    jo.getString("sjje")
//                    );
//        }
//
//
//    }

}
//
//class MySSLSocketFactory implements ProtocolSocketFactory {
//    static {
//        System.out.println(">>>>in MySSLSocketFactory>>");
//    }
//    private SSLContext sslcontext = null;
//
//    private SSLContext createSSLContext() {
//        SSLContext sslcontext = null;
//        try {
//            sslcontext = SSLContext.getInstance("SSL");
//            sslcontext.init(null,
//                    new TrustManager[] { new TrustAnyTrustManager() },
//                    new java.security.SecureRandom());
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        } catch (KeyManagementException e) {
//            e.printStackTrace();
//        }
//        return sslcontext;
//    }
//
//    private SSLContext getSSLContext() {
//        if (this.sslcontext == null) {
//            this.sslcontext = createSSLContext();
//        }
//        return this.sslcontext;
//    }
//
//    public Socket createSocket(Socket socket, String host, int port,
//                               boolean autoClose) throws IOException, UnknownHostException {
//        return getSSLContext().getSocketFactory().createSocket(socket, host,
//                port, autoClose);
//    }
//
//    public Socket createSocket(String host, int port) throws IOException,
//            UnknownHostException {
//        return getSSLContext().getSocketFactory().createSocket(host, port);
//    }
//
//    public Socket createSocket(String host, int port, InetAddress clientHost,
//                               int clientPort) throws IOException, UnknownHostException {
//        return getSSLContext().getSocketFactory().createSocket(host, port,
//                clientHost, clientPort);
//    }
//
//    public Socket createSocket(String host, int port, InetAddress localAddress,
//                               int localPort, HttpConnectionParams params) throws IOException,
//            UnknownHostException, ConnectTimeoutException {
//        if (params == null) {
//            throw new IllegalArgumentException("Parameters may not be null");
//        }
//        int timeout = params.getConnectionTimeout();
//        SocketFactory socketfactory = getSSLContext().getSocketFactory();
//        if (timeout == 0) {
//            return socketfactory.createSocket(host, port, localAddress,
//                    localPort);
//        } else {
//            Socket socket = socketfactory.createSocket();
//            SocketAddress localaddr = new InetSocketAddress(localAddress,
//                    localPort);
//            SocketAddress remoteaddr = new InetSocketAddress(host, port);
//            socket.bind(localaddr);
//            socket.connect(remoteaddr, timeout);
//            return socket;
//        }
//    }
//
//    private static class TrustAnyTrustManager implements X509TrustManager {
//
//        public void checkClientTrusted(X509Certificate[] chain, String authType)
//                throws CertificateException {
//        }
//
//        public void checkServerTrusted(X509Certificate[] chain, String authType)
//                throws CertificateException {
//        }
//
//        public X509Certificate[] getAcceptedIssuers() {
//            return new X509Certificate[] {};
//        }
//    }
//}
